剛開始接觸 NodeJS,紀錄一下心得
//==========匯入modules=========
var querystring = require('querystring');
var url = require('url');
var http = require('http');
var https = require('https');
var util = require('util');
//=========POST URL=========
var urlstr = 'url';
//=========POST 内容=========
var bodyQueryStr = {
"key1": "content1",
"key2": "content2"
};
var contentStr = JSON.stringify(bodyQueryStr);
var contentLen = Buffer.byteLength(contentStr, 'utf8');
console.log(util.format('post data: %s, with length: %d', contentStr, contentLen));
var httpModule = urlstr.indexOf('https') === 0 ? https : http;
var urlData = url.parse(urlstr);
//=========HTTP請求選項=========
var opt = {
hostname: urlData.hostname,
path: urlData.path,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': contentLen
}
};
//=========處理事件回覆=========
var req = httpModule.request(opt, function(httpRes) {
var buffers = [];
httpRes.on('data', function(result) {
buffers.push(result);
});
httpRes.on('end', function() {
var wholeData = Buffer.concat(buffers);
var dataStr = wholeData.toString('utf8');
console.log('content ' + dataStr);
});
}).on('error', function(err) {
console.log('error ' + err);
});
//=========傳送資料,完成發送=========
req.write(contentStr);
req.end();